package com.plugins.utils.plugin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.plugins.App;
import com.plugins.pluginlib.internal.IPluginPackage;
import com.plugins.pluginlib.utils.JsonUtil;
import com.plugins.utils.FileUtil;
import com.plugins.utils.plugin.bean.PluginInfo;
import com.plugins.utils.plugin.callback.PluginMessageCallback;
import com.plugins.pluginlib.broadcast.BroadMessage;
import com.plugins.pluginlib.broadcast.BroadcastManager;
import com.plugins.pluginlib.internal.IIntent;
import com.plugins.pluginlib.internal.IPluginManager;
import com.plugins.pluginlib.utils.IConstants;
import com.plugins.pluginlib.utils.ImageUtil;
import com.plugins.pluginlib.utils.PluginUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 插件管理
 */
public class PluginsManager {
    private static final String TAG = PluginsManager.class.getSimpleName();
    //是否加载完成
    private String PLUGIN_SUFFIX = ".apk";
    private static PluginsManager pluginsManager;
    public static PluginsManager getInstance(){
        if(pluginsManager ==null){
            synchronized (PluginsManager.class){
                if(pluginsManager ==null){
                    pluginsManager = new PluginsManager();
                }
            }
        }
        return pluginsManager;
    }

    /**
     * 获取插件信息
     * @param plugin
     * @return
     */
    public PluginInfo getPluginInfo(File plugin){
        PluginInfo pluginInfo = new PluginInfo();
        pluginInfo.setName(plugin.getName().substring(0,plugin.getName().lastIndexOf(".")));
        pluginInfo.setPluginPath(plugin.getAbsolutePath());
        PackageInfo packageInfo = PluginUtils.getPackageInfo(App.getApp(), pluginInfo.getPluginPath());
        if(packageInfo!=null) {
            try {
                pluginInfo.setPackageName(packageInfo.packageName);
                pluginInfo.setVersionName(packageInfo.versionName);
                pluginInfo.setVersionCode(packageInfo.versionCode);
                if (packageInfo.activities != null && packageInfo.activities.length > 0) {
                    Drawable appIcon = packageInfo.applicationInfo.loadIcon(App.getApp().getPackageManager());
                    String path = FileUtil.getPath()+"/" + pluginInfo.getName() + ".png";
                    String iconPath = ImageUtil.saveIcon(path, appIcon);
                    pluginInfo.setIconResource(iconPath);
                }
            } catch (Exception e) {

            }
        }
        return pluginInfo;
    }
    private Map<String,String> pluginPackageNames = new HashMap<>();
    /**
     * 打开插件
     * @param pluginName
     * @param data
     * @param pluginCallback
     */
    public void openPlugin(String pluginName, BroadMessage data, PluginMessageCallback pluginCallback){
        String packageName="";
        String pluginPath = FileUtil.getPath()+pluginName;
        File file = new File(pluginPath);
        //检查apk格式的文件
        int  result;
        if (file.exists()&&file.getAbsolutePath().lastIndexOf(".apk") !=-1) {
            IPluginManager pluginManager = IPluginManager.getInstance(App.getApp());
            //先加载dex
            IPluginPackage iPluginPackage =  IPluginManager.getInstance(App.getApp()).loadApk(file.getAbsolutePath());
            packageName = iPluginPackage.packageName;
            pluginPackageNames.put(pluginName,packageName);
            IIntent iIntent = new IIntent(iPluginPackage.packageName,  iPluginPackage.defaultActivity);
            iIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            iIntent.putExtra(IConstants.EXTRA_FROM_HOST_MESSAGE, JsonUtil.beanToJson(data));
            iIntent.putExtra(IConstants.EXTRA_PACKNAME,iPluginPackage.packageName);
            result = pluginManager.startActivity(App.getApp(), iIntent);
        }else{
            result = IPluginManager.START_RESULT_NO_LAUNCHER;
        }

        BroadMessage pluginData = new BroadMessage();
        pluginData.setResult(result);
        switch (result){
            case IPluginManager.START_RESULT_SUCCESS:
                resigisterMessageListener(App.getApp(),packageName,pluginCallback);
                pluginData.setSuccess(true);
                pluginData.setMessage("加载成功");
                break;
            case IPluginManager.START_RESULT_NO_PKG:
                pluginData.setMessage("没找到插件包");
                pluginData.setSuccess(false);
                break;
            case IPluginManager.START_RESULT_NO_CLASS:
                pluginData.setMessage("没找到class");
                pluginData.setSuccess(false);
                break;
            case IPluginManager.START_RESULT_TYPE_ERROR:
                pluginData.setMessage("加载出错");
                pluginData.setSuccess(false);
                break;
            case IPluginManager.START_RESULT_NO_LAUNCHER:
                pluginData.setMessage("没找到启动项，需在插件AndroidManifest.xml的launcher启动activity或service加入meta-data{name=statement,value=PLUGIN_LAUNCHER}的配置。");
                pluginData.setSuccess(false);
                break;
            default:
                pluginData.setMessage("加载失败");
                pluginData.setSuccess(false);
                break;
        }
        pluginCallback.onResult(pluginData);
    }


    /**
     * 注册消息监听
     * @param packageName
     * @param pluginCallback
     */
    private Set<String> resigisterActions = new HashSet<>();
    private void resigisterMessageListener(Context context, String packageName, PluginMessageCallback pluginCallback){
        initBroadcastManager(context);
        String action = IConstants.PLUGIN_PUSH_MESSAGE_SUFFIX+packageName;
        resigisterActions.add(action);
        broadcastManager.unregister(action);
        broadcastManager.register(action, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                BroadMessage broadMessage = broadcastManager.getBroadMessage(intent);
                if(pluginCallback!=null){
                    pluginCallback.onResult(broadMessage);
                }
            }
        });
    }

    /**
     * 向模块发送消息
     * @param pluginName
     * @param message
     */
    public void sendMessage(String pluginName,BroadMessage message) throws  Exception{
        String packageName =pluginPackageNames.get(pluginName);
        if(packageName==null){
            throw new Exception("插件:"+pluginName+"未打开.");
        }
        initBroadcastManager(App.getApp());
        String action = IConstants.HOST_PUSH_MESSAGE_SUFFIX+packageName;
        Log.d("sendMessage",action);
        Log.d("sendMessage", JSON.toJSONString(message));
        broadcastManager.sendBroadcast(action,message);
    }

    /**
     * 初始化广播
     */
    private BroadcastManager broadcastManager;
    private void initBroadcastManager(Context context){
        if(broadcastManager==null){
            broadcastManager = BroadcastManager.getInstance(context);
        }
    }



    /**
     * 销毁
     * @param context
     */
    public void onDestory(Context context){
        if(broadcastManager!=null){
            for(String action:resigisterActions) {
                broadcastManager.unregister(action);
            }
        }
    }

    /**
     * 去除插件环境
     * @param pluginName
     */
    public void removePlugin(String pluginName) {
        String packageName =pluginPackageNames.get(pluginName);
        if(packageName!=null){
            pluginPackageNames.remove(pluginName);
            IPluginManager.getInstance(App.getApp()).removePluginEnv(packageName);
        }
    }
}
